import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, Row, Col, DatePicker } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, EditOutlined, PlusOutlined, PrinterOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { Option } = Select;
const { RangePicker } = DatePicker;
const {TextArea} = Input;

// 获取会员卡列表
const fetchCards = async (params) => {
  return request('/api/v1/member/card', {
    method: 'GET',
    params,
  });
};

// 获取会员卡详情
const fetchCardDetail = async (id) => {
  return request(`/api/v1/member/card/${id}`, {
    method: 'GET',
  });
};

// 创建会员卡
const createCard = async (data) => {
  return request('/api/v1/member/card', {
    method: 'POST',
    data,
  });
};

// 更新会员卡
const updateCard = async (data) => {
  return request(`/api/v1/member/card/${data.id}`, {
    method: 'PUT',
    data,
  });
};

// 获取会员列表
const fetchMembers = async (params) => {
  return request('/api/v1/member', {
    method: 'GET',
    params: { ...params, pageSize: 100 },
  });
};

// 获取会员等级列表
const fetchLevels = async () => {
  return request('/api/v1/member/level', {
    method: 'GET',
    params: { status: 1 },
  });
};

const MemberCard = () => {
  const [cards, setCards] = useState([]);
  const [members, setMembers] = useState([]);
  const [levels, setLevels] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [cardForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentCard, setCurrentCard] = useState(null);
  const [formTitle, setFormTitle] = useState('创建会员卡');

  // 获取会员卡列表
  const fetchCardList = async () => {
    try {
      setLoading(true);
      const res = await fetchCards({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setCards(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取会员卡列表失败');
      }
    } catch (error) {
      console.error('获取会员卡列表出错:', error);
      message.error('获取会员卡列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取会员列表
  const fetchMemberList = async () => {
    try {
      const res = await fetchMembers({});
      if (res.success) {
        setMembers(res.data.list || []);
      } else {
        message.error(res.message || '获取会员列表失败');
      }
    } catch (error) {
      console.error('获取会员列表出错:', error);
      message.error('获取会员列表失败');
    }
  };

  // 获取会员等级列表
  const fetchLevelList = async () => {
    try {
      const res = await fetchLevels();
      if (res.success) {
        setLevels(res.data.list || []);
      } else {
        message.error(res.message || '获取会员等级列表失败');
      }
    } catch (error) {
      console.error('获取会员等级列表出错:', error);
      message.error('获取会员等级列表失败');
    }
  };

  useEffect(() => {
    fetchCardList();
    fetchMemberList();
    fetchLevelList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 查看会员卡详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchCardDetail(record.id);
      if (res.success) {
        setCurrentCard(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取会员卡详情失败');
      }
    } catch (error) {
      console.error('获取会员卡详情出错:', error);
      message.error('获取会员卡详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理添加会员卡
  const handleAdd = () => {
    setFormTitle('创建会员卡');
    setCurrentCard(null);
    cardForm.resetFields();
    cardForm.setFieldsValue({
      validity_period: 12, // 默认有效期12个月
      status: 'active',
    });
    setFormVisible(true);
  };

  // 处理编辑会员卡
  const handleEdit = (record) => {
    setFormTitle('编辑会员卡');
    setCurrentCard(record);
    cardForm.resetFields();
    cardForm.setFieldsValue({
      member_id: record.member_id,
      card_no: record.card_no,
      level_id: record.level_id,
      validity_period: record.validity_period,
      expiry_date: record.expiry_date ? moment(record.expiry_date) : null,
      status: record.status,
      remark: record.remark,
    });
    setFormVisible(true);
  };

  // 提交表单
  const handleFormSubmit = async () => {
    try {
      const values = await cardForm.validateFields();
      setLoading(true);
      
      // 处理日期格式
      if (values.expiry_date) {
        values.expiry_date = parseInt(values.expiry_date.format('X'));
      }
      
      let res;
      if (currentCard) {
        // 更新
        res = await updateCard({
          id: currentCard.id,
          ...values,
        });
      } else {
        // 创建
        res = await createCard(values);
      }
      
      if (res.success) {
        message.success(`${currentCard ? '更新' : '创建'}会员卡成功`);
        setFormVisible(false);
        fetchCardList();
      } else {
        message.error(res.message || `${currentCard ? '更新' : '创建'}会员卡失败`);
      }
    } catch (error) {
      console.error(`${currentCard ? '更新' : '创建'}会员卡出错:`, error);
      message.error(`${currentCard ? '更新' : '创建'}会员卡失败`);
    } finally {
      setLoading(false);
    }
  };

  // 处理打印会员卡
  const handlePrint = (record) => {
    message.success('会员卡打印功能已触发');
    // 实际打印功能需要根据具体需求实现
  };

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.keyword) {
      params.keyword = values.keyword;
    }
    if (values.levelId) {
      params.levelId = values.levelId;
    }
    if (values.status) {
      params.status = values.status;
    }
    if (values.dateRange && values.dateRange.length === 2) {
      params.startTime = values.dateRange[0].format('YYYY-MM-DD');
      params.endTime = values.dateRange[1].format('YYYY-MM-DD');
    }
    
    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 表格列定义
  const columns = [
    {
      title: '卡号',
      dataIndex: 'card_no',
      key: 'card_no',
      width: 120,
    },
    {
      title: '会员姓名',
      dataIndex: 'member_id',
      key: 'member_id',
      width: 180,
      render: (text, record) => {
        const member = members.find(m => m.id === text);
        return member ? `${member.name }(${member.phone})`: text;
      },
    },
    {
      title: '会员等级',
      dataIndex: 'level_id',
      key: 'level_id',
      width: 120,
      render: (text, record) => {
        const level = levels.find(l => l.id === text);
        let color = 'blue';
        if (level) {
          switch (level.code) {
            case 'gold':
              color = 'gold';
              break;
            case 'platinum':
              color = 'purple';
              break;
            case 'diamond':
              color = 'cyan';
              break;
            default:
              color = 'blue';
          }
          return <Tag color={color}>{level.name}</Tag>;
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '有效期',
      dataIndex: 'validity_period',
      key: 'validity_period',
      width: 100,
      render: (text) => `${text}个月`,
    },
    {
      title: '到期日期',
      dataIndex: 'expiry_date',
      key: 'expiry_date',
      width: 120,
      render: (text) => text ? moment(text*1000).format('YYYY-MM-DD') : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        let color = '';
        let text = '';
        // 处理数值状态码或字符串状态
        if (typeof status === 'number') {
          switch (status) {
            case 1:
              color = 'green';
              text = '正常';
              break;
            case 2:
              color = 'orange';
              text = '已过期';
              break;
            case 0:
              color = 'red';
              text = '禁用';
              break;
            default:
              color = 'default';
              text = '未知';
          }
        } 
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            icon={<PrinterOutlined />} 
            onClick={() => handlePrint(record)}
          >
            打印
          </Button>
        </Space>
      ),
    },
  ];

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card style={{ marginBottom: 24 }}>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="keyword" label="关键词">
            <Input placeholder="卡号/会员姓名" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="levelId" label="会员等级">
            <Select placeholder="请选择会员等级" style={{ width: 150 }} allowClear>
              {levels.map(level => (
                <Option key={level.id} value={level.id}>{level.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 150 }} allowClear>
              <Option value={1}>正常</Option>
              <Option value={2}>已过期</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="创建时间">
            <RangePicker style={{ width: 250 }} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                查询
              </Button>
              <Button onClick={handleReset} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            创建会员卡
          </Button>
        </div>
        
        <Table
          columns={columns}
          dataSource={cards}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1300 }}
        />
      </Card>

      {/* 会员卡详情弹窗 */}
      <Modal
        title="会员卡详情"
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={700}
      >
        {currentCard && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="卡号" span={2}>{currentCard.card_no}</Descriptions.Item>
            <Descriptions.Item label="会员姓名">{members.find(m => m.id === currentCard.member_id)?.name}</Descriptions.Item>
            <Descriptions.Item label="会员等级">
              {(() => {
                const level = levels.find(l => l.id === currentCard.level_id);
                let color = 'blue';
                if (level) {
                  switch (level.code) {
                    case 'gold':
                      color = 'gold';
                      break;
                    case 'platinum':
                      color = 'purple';
                      break;
                    case 'diamond':
                      color = 'cyan';
                      break;
                    default:
                      color = 'blue';
                  }
                  return <Tag color={color}>{level.name}</Tag>;
                }
                return <Tag color={color}>{currentCard.level_id}</Tag>;
              })()}
            </Descriptions.Item>
            <Descriptions.Item label="有效期">{`${currentCard.validity_period}个月`}</Descriptions.Item>
            <Descriptions.Item label="到期日期">{currentCard.expiry_date}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={
                (currentCard.status === 'active' || currentCard.status === 1) ? 'green' :
                (currentCard.status === 'expired' || currentCard.status === 2) ? 'orange' :
                (currentCard.status === 'suspended' || currentCard.status === 0) ? 'red' : 'default'
              }>
                {(currentCard.status === 'active' || currentCard.status === 1) ? '正常' :
                 (currentCard.status === 'expired' || currentCard.status === 2) ? '已过期' :
                 (currentCard.status === 'suspended' || currentCard.status === 0) ? '禁用' : '未知'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{moment(currentCard.created_at*1000).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            <Descriptions.Item label="备注" span={2}>{currentCard.remark || '-'}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 会员卡表单弹窗 */}
      <Modal
        title={formTitle}
        visible={formVisible}
        onCancel={() => setFormVisible(false)}
        onOk={handleFormSubmit}
        confirmLoading={loading}
        width={700}
      >
        <Form
          form={cardForm}
          layout="vertical"
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="member_id"
                label="会员"
                rules={[{ required: true, message: '请选择会员' }]}
              >
                <Select placeholder="请选择会员">
                  {members.map(member => (
                    <Option key={member.id} value={member.id}>{member.name} ({member.phone})</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="card_no"
                label="卡号"
                rules={[{ required: true, message: '请输入卡号' }]}
              >
                <Input placeholder="请输入卡号" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="level_id"
                label="会员等级"
                rules={[{ required: true, message: '请选择会员等级' }]}
              >
                <Select placeholder="请选择会员等级">
                  {levels.map(level => (
                    <Option key={level.id} value={level.id}>{level.name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="validity_period"
                label="有效期(月)"
                rules={[{ required: true, message: '请输入有效期' }]}
              >
                <Select placeholder="请选择有效期">
                  <Option value={3}>3个月</Option>
                  <Option value={6}>6个月</Option>
                  <Option value={12}>12个月</Option>
                  <Option value={24}>24个月</Option>
                  <Option value={36}>36个月</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="expiry_date"
                label="到期日期"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value={2}>已过期</Option>
                  <Option value={1}>正常</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="remark"
            label="备注"
          >
            <TextArea rows={3} placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default MemberCard;